﻿package send;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Iterator;

import org.json.simple.JSONObject;

import queue.KSocketQueueCenter;

public class Sender {

	static private Sender instance;

	// private ArrayList outputArrayList;

	public Sender() {
		// outputArrayList = new ArrayList();
	}

	static public Sender GetInstance() {
		if (instance == null) {
			instance = new Sender();
		}
		return instance;
	}

	public void sendTest(Socket _sSocket, String msg) throws IOException {

		JSONObject obj2 = new JSONObject();
		obj2.put("Type", 10001);

		String sendmsg = obj2.toString();
		try {
			sendMessage(_sSocket, sendmsg.getBytes());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 单发
	 * 
	 * @param _sSocket
	 */
	public void onlySend(Socket _sSocket, String msg) throws IOException {

		try {
			sendMessage(_sSocket, msg.getBytes());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 广播消息
	 * 
	 * @param msg
	 */
	public void Broadcast(String msg) throws IOException {

		for (Iterator iterator = KSocketQueueCenter.GetInstance()
				.getOnLineList().values().iterator(); iterator.hasNext();) {
			Socket _sSocket = (Socket) iterator.next();
			onlySend(_sSocket, msg);
		}
	}

	public void sendMessage(Socket socket, byte[] bytes) throws Exception {

		DataOutputStream dataOutput = new DataOutputStream(
				socket.getOutputStream());
		// 编写数据的长度
		int lengths=bytes.length;
		dataOutput.writeInt(lengths);
		dataOutput.write(bytes);
		dataOutput.flush();
	}
	// / end class
}